package com.cnt.util;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Component
public class FileUtil {

    private static final int BUFFER_SIZE = 8192; // 缓冲区大小

    //word2pdf
    public File convertToPdf(File inputWord) {
        try (InputStream docxInputStream = new FileInputStream(inputWord);
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             FileOutputStream fileOutputStream = new FileOutputStream("output.pdf");
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, BUFFER_SIZE)) {
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            byte[] pdfBytes = outputStream.toByteArray();
            bufferedOutputStream.write(pdfBytes);
            return new File("output.pdf");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    public byte[] addWatermarkToPDF(File inputFile, String waterMarkName) throws Exception {
        try {
            // 水印的高和宽（参数可调节）
            int textH = 75;
            int textW = 170;
            // 间隔距离（参数可调节）
            int interval = 30;

            FileInputStream fileInputStream = new FileInputStream(inputFile);
            PdfReader reader = new PdfReader(new BufferedInputStream(fileInputStream, BUFFER_SIZE));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);//填充透明度
            gs.setStrokeOpacity(0.4f);//线条透明度
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                // 在内容下方加水印
                //under = stamper.getUnderContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 20);
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, width - textW,
                                height - textH, 30);
                    }
                }
                // 添加水印文字
                under.endText();
                System.out.println("success");
            }
            stamper.close();
            reader.close();
            fileInputStream.close();
            return outputStream.toByteArray();
        } catch (Exception e) {
            throw e;
        }
    }

    public File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(multipartFile.getOriginalFilename());
        try (FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE)) {
            bos.write(multipartFile.getBytes());
        }
        return file;
    }
}
